import React from 'react';
import {observable,action,toJS} from 'mobx';
import {inject, observer} from 'mobx-react';
import { WeaLocaleProvider, WeaFormItem,WeaBrowser,WeaDialog,WeaTools,WeaTab,WeaTop,WeaInput,WeaNewScroll,WeaSearchGroup,WeaHelpfulTip } from 'ecCom'; 
import { Button, Modal, message } from 'antd';
import {WeaTableNew,WeaForm,WeaSwitch} from 'comsMobx';
import './style';
const WeaTable = WeaTableNew.WeaTable;
const {TableStore} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

class DemoStore {
  @observable form = new WeaForm();
  @observable conditioninfo = [];
  @observable addEditloading = false;
  @observable add_edit_type = '';
  @observable recordId = '';
  @observable tableStore = new TableStore();
  @observable canSet = false; // 获取“人员状态来源维护”用户的权限
  @observable adForm = new WeaForm();
  @observable adSearchConditions = [];
  @observable browser_select_datasources = '';
  @observable setDataParams = [];
  @action
  getFormParams() {
    return this.form.getFormParams();
  }

  setParams = (params={}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
  }

  getAddDatas = (params) => { // 获取新建数据来源表单数据
    this.addEditloading = true;
    WeaTools.callApi('/api/portal/element/hdpanel/getEditDataSource', 'POST', {...params}).then(result => {
      this.addEditloading = false;
      let field = result.fields ? toJS(result.fields) : [];
      this.conditioninfo = field;
      this.form.initFormFields(field);
    });
  }

  saveDatas = (param, callback) => { // 保存新建数据来源表单的数据
    let params = {...param};
    if(this.add_edit_type == 'edit') {
      params = {...param,id: this.recordId};
    }
    WeaTools.callApi('/api/portal/element/hdpanel/addAndEditDS', 'POST', params).then(result => {
      if(result.api_status) {
        message.success(getLabel(22619,'保存成功'));
        typeof(callback) == 'function' && callback()
        this.form.resetForm();
      }else{
        message.error(getLabel(22620,'保存失败'));
      }
    });
  }

  getTableStore = (params, callback) => { // 获取数据来源管理数据
    WeaTools.callApi('/api/portal/element/hdpanel/getHDPanelDSTableList', 'POST', {...params}).then(result => {
      // const {tableStore} = this.state;
      this.tableStore.getDatas(result.sessionkey, 1);
    });
    // 
    typeof(callback) === 'function' && callback();
  }

  getAdvanceDatas = () => { // 获取数据来源管理--高级搜索
    WeaTools.callApi('/api/portal/element/hdpanel/getHDPanelDSConditionInfo', 'POST', {}).then(result => {
      let field = result.conditioninfo ? toJS(result.conditioninfo) : [];

      this.adSearchConditions = field;
      this.adForm.initFormFields(field);
    });
  }
 
  deleteDatas = (id, callback) => {
    const Delete = (ids) => WeaTools.callApi('/api/portal/element/hdpanel/deleteDS', 'POST', {id: ids}).then(result => {
      if(result.api_status) {
        message.success(getLabel(20461,'删除成功'));
         // 刷新
        this.getTableStore(); // 刷新
        typeof(callback) === 'function' && callback();
      }else{
        message.error(getLabel(20462,'删除失败'));
      }
    });

    Modal.confirm({
      title: getLabel(15097,'确定要删除吗？'),
      onOk: () => Delete(id),
    });
  }

  saveSettingDate = (params) => { // 保存元素设置数据
    WeaTools.callApi('/api/portal/element/hdpanel/saveSettingDate', 'POST', {...params}).then(result => {
      if(result.api_status) {
        message.success(getLabel(22619,'保存成功'));
      }else{
        message.error(getLabel(22620,'保存失败'));
      }
    })
  }

  getSettingDate = (params) => { // 获取元素设置数据
    WeaTools.callApi('/api/portal/element/hdpanel/getSettingDate', 'POST', {...params}).then(result => {
      this.setParams({canSet: result.canSet, setDataParams: result.hdpanel_data});
    })
  }

}

const demoStore = new DemoStore();

@observer
class Setting extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          visible: false,
          showSearchAd: false,
          addVisible: false,
          savebtnVisible: false,
          
          eid: this.props.params.eid, // 门户元素id传参数
        };
        // 获取父组件的保存按钮
        props.getInstance && props.getInstance(this);
        this.onSave = this.onSave.bind(this);
    }

    componentWillMount() {
      const {getSettingDate} = demoStore;
      getSettingDate({eid: this.state.eid||'19'});
      // getAdvanceDatas();
    }

    onSave = () => {
      const {browser_select_datasources,saveSettingDate,setDataParams} = demoStore;
      const {eid} = this.state;
      let params = {
        hdpanel_data: browser_select_datasources || setDataParams[0]&&setDataParams[0].id,
        eid: eid,
      };
      saveSettingDate(params);
    }

    getSettingDate = () => {
      const {getSettingDate} = demoStore;
      const {eid} = this.state;
      let params = {eid: eid};
      getSettingDate(params);
    }

    setOnOperatesClick = (record,index,operate,flag) => {
      const {getAddDatas, setParams, deleteDatas} = demoStore;
      if(flag == '0') { // 查看
        this.setState({addVisible: true,savebtnVisible: false}, ()=>getAddDatas({id: record.id}));
        setParams({add_edit_type: 'preview'});
      }if(flag == '1') { // 编辑
        this.setState({addVisible: true,savebtnVisible: true}, ()=>getAddDatas({id: record.id}));
        setParams({add_edit_type: 'edit', recordId: record.id});
      }else if(flag == '2') { // 删除
        deleteDatas(record.id, () => this.refs.dataSources.reload());
        setParams({add_edit_type: 'delete'});
      }
    }

    getColumns = (columns) => {
      let newColumns = '';
      newColumns = columns.map(column => {
        let newColumn = column;
        //表格的标题列的前端元素改造
        if (newColumn.dataIndex === 'name') {
          newColumn.render = (text, record, index) => {
            //通过record获取到当前行相对应的name
            const name = record.namespan.replace(/<([^<>]+)>/g, ''); // namespan
            return (
              <div className="wea-url noWrap" title={name}>
                <a
                  href="javascript:;"
                  onClick={() => {
                    let flag = record.issystem == '1' ? '0' : '1'; // 1: 编辑， 0: 删除
                    this.setOnOperatesClick(record,'','',flag);
                  }}
                  className="noWrap"
                  title={name}
                >
                  {name}
                </a>
              </div>
            );
          };
        }
        return newColumn;
      });
    }

    add_edit_form = (loading) => {
      const { form, conditioninfo } = demoStore;
      const {isFormInit} = form;
      let group = [];
      isFormInit && toJS(conditioninfo).map((c, _index) =>{
        let items = [];
        c.items.map(field => {
          let col = 1;
          if (field.conditionType.toUpperCase() == WeaTools.types.CASCADER) col = 1;
          let titile = field.domkey[0] == 'sqlStr' ? <span>{field.label}<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@vmazy9@${field.domkey[0]}`} width={400} title={getLabel(505891,'查询SQL语句中必须返回的字段名包括hrmid,content,startdate,starttime,enddate,endtime,color')}/></span> : field.label;
          items.push({
            com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@kltlnt@${field.domkey[0]}`}
                label={titile}
                labelCol={{span: `${field.labelcol}`}}
                ratio1to2
                error={form.getError(field)}
                tipPosition="bottom"
                wrapperCol={{span: `${field.fieldcol}`}}>
                  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@saxtrb@${field.domkey[0]}`} fieldConfig={field} form={form} onChange={this.onChange.bind(this)} onBlur={this.onBlur.bind(this)}/>
                </WeaFormItem>),
            col:col,
            hide: form.isHide(field, (keys, allParams)=> {
              return false;
            })
          })
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@920z6n@${_index}`} needTigger={false} title={c.title} showGroup={c.defaultshow} items={items}/>)
      });
      return group;
    }

    saveAddDatas = () => {
      const {getTableStore} = demoStore;
      let Base64 = ecCom.WeaTools.Base64
      const doupdate = () => { // 保存成功后的回调
        getTableStore('', () => this.setState({visible: true}));
        this.refs.dataSources.reload();
        this.setState({addVisible: false});
      }
      const {form, saveDatas} = demoStore;
      let params = form.getFormParams();

      if(params.name == '' || params.sqlStr == '') {
        Modal.warning({
          title: `${getLabel(127354,'警告')}`,
          content: getLabel(505887,'必填未填写！'),
        });
      }else{
        params = {...params, sqlStr: Base64.encode(params.sqlStr)}
        saveDatas(params, () => doupdate());
      }
    }

    closeAddform = () => {
      this.setState({addVisible: false});
      const {form, saveDatas} = demoStore;
      form.resetForm();
    }

    onSearch = (data,type) => {
      // 数据来源管理
      const {getTableStore,adForm} = demoStore;
      type === 'search' && getTableStore({name: data});
      type === 'adsearch' && getTableStore(adForm.getFormParams(), ()=>this.setState({showSearchAd: false}));
    }

    setShowSearchAd = (bool) => {
      this.setState({showSearchAd: bool})
    }

    getSearchs() {
      const { adForm, adSearchConditions } = demoStore;
      const {isFormInit} = adForm;
      let group = [];
      isFormInit && toJS(adSearchConditions).map((c, _index) =>{
        let items = [];
        c.items.map(field => {
          let col = 2;
          if (field.conditionType.toUpperCase() == WeaTools.types.CASCADER) col = 1;
          items.push({
            com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@fgbbyj@${field.domkey[0]}`}
                label={`${field.label}`}
                labelCol={{span: `${field.labelcol}`}}
                ratio1to2
                error={adForm.getError(field)}
                tipPosition="bottom"
                wrapperCol={{span: `${field.fieldcol}`}}>
                  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@754xw0@${field.domkey[0]}`} fieldConfig={field} form={adForm} onChange={this.onChange.bind(this)} onBlur={this.onBlur.bind(this)}/>
                </WeaFormItem>),
            col:col,
            hide: adForm.isHide(field, (keys, allParams)=> {
              return false;
            })
          })
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@93bka2@${_index}`} needTigger={false} title={c.title} showGroup={c.defaultshow} items={items}/>)
      });
      return group;
    }

    cleardatas = () => {
      const {setParams} = demoStore;
      let datas = [{id: '', name: ' '}];

      this.refs.dataSources.set(datas);
      this.refs.dataSources.closeModal();
      setParams({browser_select_datasources: ''})
    }

    dataSourcesButtons = () => {
      let buttons = [];
      const {canSet,getTableStore,getAdvanceDatas,setParams} = demoStore;
      canSet && buttons.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i6izbx@getAdvanceDatas`} type='primary' onClick={()=> {getTableStore('', () => this.setState({visible: true})); getAdvanceDatas()}}>{getLabel(505888,'数据来源管理')}</Button>,
      );
      buttons.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wque6k@cleardatas`} onClick={()=> {this.cleardatas()}}>{getLabel(311,'清除')}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8dsv7s@closeModal`} onClick={()=> {this.refs.dataSources.closeModal()}}>{getLabel(31129,'取消')}</Button>,
      );

      return buttons;
    }

    onChange(data) {
    }

    onBlur(data) {
    }

    render() {
      const {visible,showSearchAd,addVisible,conditioninfo,form,savebtnVisible} = this.state;
      const {getAddDatas,addEditloading,setParams,tableStore,getTableStore,deleteDatas,adForm,setDataParams,getAdvanceDatas} = demoStore;
      let buttons = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kmszfi@getAddDatas`} type="primary" onClick={() => {this.setState({addVisible: true, savebtnVisible: true}, ()=>getAddDatas()); setParams({add_edit_type: 'add'});}}>{getLabel(365,'新建')}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fko73u@deleteDatas`} type="primary" disabled={toJS(tableStore.selectedRowKeys).length>0 ? false : true} onClick={()=>{deleteDatas(toJS(tableStore.selectedRowKeys), () => this.refs.dataSources.reload())}}>{getLabel(32136,'批量删除')}</Button>,
      ]; 
      let buttonsAd = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@e79tns@adsearch`} type="primary" onClick={()=>this.onSearch('','adsearch')}>{getLabel(388113,'搜索')}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j2nsme@resetForm`} type="primary" onClick={()=> adForm.resetForm()}>{getLabel(2022,'重置')}</Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xqa45p@cancel`} type="ghost" onClick={() => this.setState({ showSearchAd: false })}>{getLabel(31129,'取消')}</Button>
      ];
      let addbuttons = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@l24sze@saveAddDatas`} type="primary" onClick={() => this.saveAddDatas()}>{getLabel(30986,'保存')}</Button>,
      ];
      
      let addmoreBtn = {datas: [
        
      ]};

      return (
        <div className="portal-element-demo-setting">
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jjf473`}
              label={getLabel(30223,'选择数据来源')}
              labelCol={{span: 6}}
              wrapperCol={{span: 16}}
          >
            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@f98xxw`}
              ref='dataSources'
              title={getLabel(30223,'选择数据来源')}
              icon='icon-coms-content'
              iconBgcolor='#6d3cf7'
              type={'HDPanelDS'}
              hasAdvanceSerach
              replaceDatas={toJS(setDataParams)}
              onChange={(ids, names, datas) => {setParams({browser_select_datasources: ids})}}
              buttons={this.dataSourcesButtons()}
            />
          </WeaFormItem>

          <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@uyl49o`}
            title={getLabel(505888,'数据来源管理')}
            visible={visible}
            icon='icon-coms-content'
            iconBgcolor='#6d3cf7'
            parentClassName={'manage-dataSources'}
            style={{width: 900, height: 500}}
            onCancel={() => this.setState({ visible: false })}
          >
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@hfd2ld`}
              buttons={buttons}
            />
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@7kpuyc`}
              searchType={['base', 'advanced']}
              showSearchAd={showSearchAd}
              buttonsAd={buttonsAd}
              searchsAd={this.getSearchs()}
              setShowSearchAd={bool => this.setShowSearchAd(bool)}
              onSearch={(data) => {this.onSearch(data, 'search')}}
              advanceHeight={100}
            />
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@t91pe5`} 
              hasOrder={true}
              needScroll={true}
              comsWeaTableStore={tableStore}
              onOperatesClick={(record,index,operate,flag) => {this.setOnOperatesClick(record,index,operate,flag)}}
              getColumns={this.getColumns}
            />
          </WeaDialog>

          <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@937bt8`}
            loading={addEditloading}
            title={getLabel(505889,'新建数据来源')}
            icon='icon-coms-content'
            iconBgcolor='#6d3cf7'
            parentClassName={'add-dataSources'}
            visible={addVisible}
            buttons={savebtnVisible ? addbuttons : []}
            moreBtn={addmoreBtn}
            style={{width: 500, height: 400}}
            onCancel={() => {this.closeAddform()}}
          >
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@438nqi`} height={400} >
              {!addEditloading && this.add_edit_form()}
            </WeaNewScroll>
          </WeaDialog>
        </div>
      );
    }
}

export default Setting;
